﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tassdar.Framework.Interface.Base;
using Tassdar.Framework.Model.Base;

namespace Tassdar.Framework.Logic.Base
{
    public class LogicBase<TEntityBase> : SlimLogicBase<TEntityBase>, ILogicBase<TEntityBase>
        where TEntityBase : EntityBase, new()
    {

        public LogicBase(EFDbcontext dbContext)
        {
            DbContext = dbContext;
        }
        public LogicBase():base()
        {
                
        }
       
        public IQueryable<TEntityBase> GetSortedQueryable()
        {
            return Queryable.OrderByDescending(x => x.SortOrder);
        }

        /// <summary>
        /// 对象实体集合处理方法
        /// 该方法目前只做了简单的处理，例如第一次新增时添加创建时间，修改时更改最后的更改时间
        /// 使用者可以根据自己的业务进行扩展，例如插入人是谁等等
        /// </summary>
        /// <param name="entities">要新增修改的实体集合</param>
        /// <param name="initAdd">是否为新增</param>
        /// <param name="maxId">之前数据的最大主键值</param>
        /// <returns></returns>
        private IList<TEntityBase> WrapEntities(IList<TEntityBase> entities, bool initAdd = true, int maxId = 0)
        {
            int count = maxId;
            foreach (var entity in entities)
            {
                if (entity.LastModifyTime == null)
                {
                    entity.LastModifyTime = DateTime.Now;
                }
                if (entity.CreatedTime == null && initAdd)
                {
                    entity.CreatedTime = DateTime.Now;
                }
                count++;
                if (!entity.SortOrder.HasValue)
                    entity.SortOrder = count;
            }
            return entities;
        }

        public override ResultModel AddEntity(TEntityBase entity, bool save = true)
        {
            var list = new List<TEntityBase>();
            list.Add(entity);
            //获取之前数据的最大ID值
            int maxId = Queryable.Count() > 0 ? Queryable.Max(x => x.Id) : 0;
            return base.AddEntity(WrapEntities(list,true,maxId)[0], save);
        }

        public override ResultModel AddEntities(IList<TEntityBase> entities, bool save = true, bool skipInvalid = true)
        {
            int maxId = Queryable.Count() > 0 ? Queryable.Max(x => x.Id) : 0;
            var list = WrapEntities(entities, true, maxId);
            return base.AddEntities(list, save);
        }
        public override ResultModel EditEntity(TEntityBase entity, bool save = true)
        {
            var list = new List<TEntityBase>();
            list.Add(entity);
            return base.EditEntity(WrapEntities(list, false)[0], save);
        }     
    }
}
